package com.yb.project.system.controller;

import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.yb.common.domain.AjaxObject;
import com.yb.common.domain.PageResult;
import com.yb.common.domain.ZTreeV3;
import com.yb.common.utils.StringUtil;
import com.yb.framework.log.annotation.Log;
import com.yb.framework.log.enums.OperateTypeEnum;
import com.yb.framework.security.utils.SecurityUtil;
import com.yb.project.base.controller.BaseController;
import com.yb.project.system.domain.SysMenu;
import com.yb.project.system.domain.SysRole;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

@Controller
@RequestMapping("/system/role")
@Api(tags = "角色管理")
public class SysRoleController extends BaseController {
	
	Logger logger = LoggerFactory.getLogger(SysRoleController.class.getName());
	
	private static String SYS_ROLE = "system/role/role";
	private static String SYS_ROLE_ADD = "system/role/role_add";
	private static String SYS_ROLE_EDIT = "system/role/role_edit";
	
	@GetMapping()
	@PreAuthorize("hasAuthority('system:role')")
	public String main() {
		return SYS_ROLE;
	}
	
	@GetMapping("/add_view")
	@PreAuthorize("hasAuthority('system:role:add')")
	public String addView() {
		return SYS_ROLE_ADD;
	}
	
	@GetMapping("/edit_view/{id}")
	@PreAuthorize("hasAuthority('system:role:edit')")
	public String editView(@PathVariable("id") Long id, ModelMap model) {
		model.put("sysRole", sysRoleService.getById(id));
		return SYS_ROLE_EDIT;
	}
	
	/**
	 * 角色列表
	 */
	@PostMapping("/list")
	@PreAuthorize("hasAuthority('system:role:list')")
	@ApiOperation(value="分页查询", notes="分页查询角色信息")
	public @ResponseBody PageResult list(SysRole sysRole) {
		startPage();
		return getPageInfo(sysRoleService.getPageByEntity(sysRole));
	}
	
	/**
	 * 新增角色
	 */
	@PostMapping("/add")
	@PreAuthorize("hasAuthority('system:role:add')")
	@ApiOperation(value="新增角色", notes="新增角色信息")
	@Log(label = "新增角色", operateType = OperateTypeEnum.ADD)
	public @ResponseBody AjaxObject add(SysRole sysRole) {
		return toAjax(sysRoleService.insert(sysRole), "新增角色" + "[" + sysRole.getName() + "]");
	}
	
	/**
	 * 编辑角色
	 */
	@PostMapping("/edit")
	@PreAuthorize("hasAuthority('system:role:edit')")
	@ApiOperation(value="编辑角色", notes="编辑角色信息")
	@Log(label = "编辑角色", operateType = OperateTypeEnum.EDIT)
	public @ResponseBody AjaxObject edit(SysRole sysRole) {
		return toAjax(sysRoleService.update(sysRole), "编辑角色" + "[" + sysRole.getName() + "]");
	}
	
	/**
	 * 删除角色
	 */
	@PostMapping("/delete")
	@PreAuthorize("hasAuthority('system:role:delete')")
	@ApiOperation(value="删除角色", notes="批量删除角色信息")
	@Log(label = "删除角色", operateType = OperateTypeEnum.DELETE)
	public @ResponseBody AjaxObject delete(@RequestParam("ids") String ids) {
		List<String> sysRoleNames = sysRoleService.getNamesByIds(StringUtil.str2LongArray(ids));
		return toAjax(sysRoleService.deleteListByIds(StringUtil.str2LongArray(ids)), "批量删除角色" + sysRoleNames);
	}
	
	/**
	 * 根据角色ID，生成菜单树
	 */
	@GetMapping("/menu_tree/{id}")
	public @ResponseBody List<ZTreeV3> sysMenuTree(@PathVariable("id") Long id) {
		List<ZTreeV3> zTreeList = new ArrayList<ZTreeV3>();
		List<SysMenu> sysMenuList = new ArrayList<SysMenu>();
		if(SecurityUtil.isAdmin()) {
			sysMenuList = sysMenuService.getAll();
		} else {
			sysMenuList = sysMenuService.getAll();
			//sysMenuList = sysMenuService.getListByPermissions(SecurityUtil.getAuthorities());
		}
		List<Long> menuIds = sysRoleMenuService.getMenuIdsByRoleId(id);
		for (SysMenu sysMenu : sysMenuList) {
			ZTreeV3 zTree = new ZTreeV3();
			zTree.setId(String.valueOf(sysMenu.getId()));
			zTree.setpId(String.valueOf(sysMenu.getPid()));
			zTree.setName(sysMenu.getText());
			zTree.setIcon(sysMenu.getIconCls());
			// 判断是否选中
			if(menuIds.contains(sysMenu.getId())) {
				zTree.setChecked(true);
			} else {
				zTree.setChecked(false);
			}
			zTreeList.add(zTree);
		}
		return zTreeList;
	}
	
	/**
	 * 角色授权（角色绑定菜单）
	 */
	@PostMapping("/set_menu")
	public @ResponseBody AjaxObject setSysMenu() {
		Long roleId = Long.valueOf(request.getParameter("roleId"));
		Long[] menuIds = StringUtil.str2LongArray(request.getParameter("menuIds"));
		sysRoleService.setMenu(roleId, menuIds);
		return AjaxObject.newOk("角色授权成功");
	}
}